package cn.wolfcode.controller;

import cn.wolfcode.annotation.LoginAnnotation;
import cn.wolfcode.cache.IUserInfoRedisService;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.service.IUserInfoService;
import cn.wolfcode.util.AssertUtil;
import cn.wolfcode.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("users")
public class UserInfoController {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @GetMapping("checkPhone")
    public Object checkPhone(String phone){
        boolean check = userInfoService.checkPhone(phone);
        return check;
    }

    @GetMapping("sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);
        return JsonResult.success();
    }

    @PostMapping("regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        return JsonResult.success();
    }


    @PostMapping("login")
    public Object login(String username,String password){
        UserInfo user = userInfoService.login(username, password);
        //创建token(唯一凭证)
        String token = userInfoRedisService.setToken(user);

        //页面需要:token user
        HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);

        return JsonResult.success(map);
    }

    @LoginAnnotation
    @GetMapping("currentUser")
    public Object currentUser(HttpServletRequest req){
        String token = req.getHeader("token");
        //通过token从redis中获取用户信息
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);

        return JsonResult.success();
    }


}
